package com.xbhog.screwdemo.demos;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
 */
@Slf4j
@RestController
public class BasicController {

    // http://127.0.0.1:8080/hello?name=lisi
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(@RequestParam(name = "name", defaultValue = "unknown user") String name) {
        return "Hello " + name;
    }

    // http://127.0.0.1:8080/user
    @RequestMapping("/user")
    @ResponseBody
    public User user() {
        User user = new User();
        user.setName("theonefx");
        user.setAge(666);
        return user;
    }

    // http://127.0.0.1:8080/save_user?name=newName&age=11
    @RequestMapping("/save_user")
    @ResponseBody
    public String saveUser(@Valid User u, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            // 获取校验不通过字段的提示信息
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            return JSON.toJSONString(fieldErrors);

        }
        return "user will save: name=" + u.getName() + ", age=" + u.getAge();
    }
    @PostMapping("/save_emp")
    public String saveEmp(@Valid @RequestBody Emp emp, BindingResult bindingResult) {
        log.info("查看入参的信息：{}", JSON.toJSONString(emp));
        if(bindingResult.hasErrors()){
            // 获取校验不通过字段的提示信息
            // 假设 bindingResult 已经填充了校验结果
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();

            // 创建一个 List 来存储每条错误信息
            List<String> errorMessages = new ArrayList<>();

            // 遍历 FieldError 列表
            for (FieldError fieldError : fieldErrors) {
                // 获取 field 和 defaultMessage
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();

                // 拼接成一条完整的错误信息
                String errorMessage = "字段位置 '" + field + "' " + defaultMessage;

                // 添加到 errorMessages 列表中
                errorMessages.add(errorMessage);
            }

            // 如果需要将所有错误信息合并成一个字符串
            return String.join("; ", errorMessages);

        }
        return "user will save: no=" + emp.getEmpNo() + ", name=" + emp.getEmpName();
    }

}
